<template>
	<view>
		<view class="head">
			<u-navbar title="服务商" :autoBack="true" :placeholder="true" leftIconColor="#000000" :titleStyle="{color: '#000000'}" :bgColor="scrollTop > 0 ? '#ffffff' : 'transparent'">
			</u-navbar>
			<view class="flex justify-between padding-tb-xl padding-left-lg padding-right text-black3">
				<view class="flex">
					<view>
						<image :src="userInfo.userAvatarUrl ? userInfo.userAvatarUrl : '/static/my/avatar.png'" mode="widthFix" class="img-100 radius-25"></image>
					</view>
					<view class="margin-left">
						<view class="font-19 text-bold flex align-center">{{userInfo.nickName}}</view>
						<view class="margin-top-sm">
							<text class="level" style="margin-left: 0;" v-if="userInfo.billLevelName">{{userInfo.billLevelName}}</text>
						</view>
						<view class="font-13 margin-top-sm">邀请码：{{userInfo.invitationCode}} <text class="copy-btn"
								@click="copyCode(userInfo.invitationCode)">复制</text></view>
					</view>
				</view>
				<view class="flex flex-direction align-end">
					<view class="flex">
						<!-- <view class="buy-btn margin-right-sm" @click="toActivation">激活</view> -->
						<view class="buy-btn fg-btn" @click="toBuy">{{userInfo.billLevel && userInfo.billLevel > 1 ? '复购' : '报单'}}</view>
					</view>
					<!-- <view class="margin-top-sm text-gray">剩余可激活：{{walletInfo.facilitatorCount || 0}}次</view> -->
				</view>
			</view>
			<view class="padding-bottom-sm">
				<u-tabs :list="list" lineColor="#e60000" :itemStyle="{width: '25%', height: '88rpx'}" :activeStyle="{color: '#e60000', 'font-weight': 'bold'}" :inactiveStyle="{color: '#333333'}" :is-scroll="false" :current="current" @change="handelTab" />
			</view>
		</view>
		<view v-if="current == 0">
			<view class="text-bold font-16 text-black3 padding">团队报单总额：{{extend.taxationMonetary || 0}}</view>
			<view class=" p-b-20 p-l-20 p-r-20 w-100 border-box btnBox">
				<u-tabs lineColor="#fff" :current="currentIndex" :itemStyle="{lineHeight:'60rpx'}" :activeStyle="{background:'#FF0804',color:'#fff'}" :inactiveStyle="{background:'#B8B8B8',color:'#fff'}" :list="listLevel" @click="levelClick"  />
			</view>
			<view class="bg-white padding margin-lr margin-bottom radius-8" v-for="(item, index ) in rankList" :key="index">
				<view class="flex justify-between font-13 text-black3">
					<view class="flex">
						<view>
							<image :src="item.userAvatarUrl ? item.userAvatarUrl : '/static/my/avatar.png'" mode="widthFix" class="img-75 radius-25"></image>
						</view>
						<view class="margin-left">
							<view class="font-15 text-bold flex align-center">
								<text class="widthName" :class="item.deleteFlag ? 'color-g':''">{{item.nickName}}</text>
								<text class="level" v-if="item.billLevelName && !item.deleteFlag">{{item.billLevelName}}</text>
								<text class="level" v-if="item.deleteFlag">已注销</text>
							</view>
							
							<view class="margin-top-sm" :class="item.deleteFlag ? 'color-g':''">手机号: {{$dealTel(item.mobile)}} </view>
							<view class="margin-top-sm" :class="item.deleteFlag ? 'color-g':''">邀请人: {{$dealTel(item.refereeMobile)}}</view>
						</view>
					</view>
					<view class="text-right">
						<view class="font-18 text-theme text-bold" :class="item.deleteFlag ? 'color-g':''">{{item.orderAmount || 0}}</view>
						<view class="text-gray margin-top-xs">总额</view>
					</view>
				</view>
				<view class="m-l-52">
					<view class="margin-top-sm" :class="item.deleteFlag ? 'color-g':''">邀请时间: {{item.createTime}}</view>
					<view class="margin-top-sm" :class="item.deleteFlag ? 'color-g':''">客户: {{item.refereeCount || 0}}</view>
				</view>
			</view>
			<empty :show="rankList.length == 0" />
		</view>

		<view class="margin-top" v-if="current == 1">
			<view class="flex justify-between align-center bg-white margin-lr padding font-13 text-black3 radius-8 margin-bottom" v-for="(item, index) in orderAwardList" :key="index">
				<view>
					<view class="font-15 text-bold">下单用户：{{$dealTel(item.fromMobile)}}</view>
					<view class="margin-top-sm">订单号：{{item.orderId}}<text class="copy-btn" @click="copyCode(item.orderId)">复制</text></view>
					<view class="margin-top-sm">下单时间：{{item.createTime}}</view>
				</view>
				<view class="buy-btn find-btn" @click="toWeeklyRecords(item)">查看</view>
			</view>
			<empty :show="orderAwardList.length == 0" />
		</view>

		<view class="margin-top" v-if="current == 2">
			<view class="flex justify-between">
				<view class="text-bold font-16 text-black3 p-t-10 p-b-10 p-l-30">
					<view>团队总业绩：</view>
					<view>{{ totalMoney || 0}}</view>
				</view>
				<view class="boxss m-t-10 m-r-20 p-l-10 p-r-10 p-t-10 p-b-10 b-r-10 flex justify-between"	@click="isShowTimeType = true">
						{{ startDateStr }}<text class="m-l-5" v-show="startDateStr!==endDateStr"> ~ {{ endDateStr }}</text>
						<image style="width: 36rpx;height: 36rpx" :style="{'transform': isSelectTime? 'rotate(180deg)': 'rotate(0deg)'}" src="@/static/index/black-arrow.png" />
				</view>
			</view>
			<view class="totalBox w-100 border-box p-30">
				<view class="flex justify-between text-center boxContent b-r-10 line-h-60 p-t-20 p-b-20 color-w">
					<view class="w-48">
						<view class="font-14 color-w line-h-60">报单总业绩</view>
						<view class="font-14 color-w line-h-60">{{ reportTotal.total || 0 }}</view>
					</view>
					<view class="borderWidth"></view>
					<view class="w-48">
						<view class="font-14 color-w line-h-60">报单单数: {{ reportTotal.count || 0 }}</view>
						<view class="font-14 color-w line-h-60">报单人数: {{ reportTotal.users || 0 }}</view>
					</view>
				</view>
				<view class="w-100 b-r-10 m-t-10 p-20 border-box">
					<view class="flex tableHeader m-b-10 p-t-20"  v-if="tableList.length !== 0">
						<view>用户</view>
						<view>时间</view>
						<view>单数</view>
						<view>金额</view>
					</view>
					<view class="flex bg-white tableContent" v-for="(item,index) in tableList" :key="index" v-if="tableList.length !== 0">
						<view>{{$dealTel(item.mobile)}}</view>
						<view>
							<view class="w-100" v-if="item.createTime">{{item.createTime.split(' ')[0]}}</view>
							<view class="w-100" v-if="item.createTime">{{item.createTime.split(' ')[1]}}</view>
						</view>
						<view>{{item.buyCount}}</view>
						<view>{{item.payAmount}}</view>
					</view>
					<empty text="没有更多了..." :show="tableList.length == 0" />
				</view>
			</view>
		</view>
		
		<view class="margin-top" v-if="current == 3">
			<view class="flex w-90 margin-center m-b-10">
				<view @click="tabChange(item)" v-for="(item,index) in teamList" :key="index" :class=" item.isActive ? 'activeStyle styleBtn ':'styleBtn'">{{ item.name }}</view>
			</view>
			<view class="color-w w-90 margin-center p-t-10 p-b-10 p-l-10 p-r-10 bg-red1 border-box b-r-10 m-b-10">
				<view class="flex font-18 font-b line-h-60">
					<view class="flex-1">总奖励：{{ teamLateralTotal.amount }}</view>
					<view class="flex-1">奖励单数：{{ teamLateralTotal.count }}</view>
				</view>
				<view class=" w-100 margin-center bg-white m-t-5 m-b-5" style="height:1rpx;"></view>
				<view class="flex font-13 font-b line-h-60">
					<view class="flex-1">贡献值：{{ teamLateralTotal.gxzAmount }}</view>
					<view class="flex-1">预消费：{{ teamLateralTotal.yxfAmount }}</view>
				</view>
			</view>
			<view class="flex justify-between align-center bg-white margin-lr padding font-13 text-black3 radius-8 margin-bottom" v-for="(item, index) in teamLateralListData" :key="index">
				<view class="w-100">
					<view class=" w-100 margin-top-sm font-b flex justify-between">
						<view class="w-80">{{item.title}}</view>
						<view class="m-l-10 flex-1 text-right">{{item.amount}}</view>
					</view>
					<view class="margin-top-sm">下单用户：{{  $dealTel(item.orderMobile) }}</view>
					<view class="margin-top-sm">
						订单号：{{item.orderId}}
						<text class="copy-btn" @click="copyCode(item.orderId)">复制</text>
					</view>
					<view class="margin-top-sm">下单时间：{{ item.orderTime }}</view>
				</view>
			</view>
			<empty :show="teamLateralListData.length == 0" />
		</view>
		
		<u-loadmore v-show="current != 2" :status="status" color="gray" class="padding-bottom-xs"/>

		<activation ref="activation"></activation>

		<!-- 弹出窗 -->
		<u-popup :show="isShowTimeType" round="10" mode="center"  borderRadius="14" :closeable="true" @close="isShowTimeType=false" :customStyle="{width:'80%'}">
				<view style="font-size: 30rpx;font-weight: bold;padding: 40rpx 40rpx 0 40rpx">请选择查询到的时间类型</view>
				<view style="padding: 40rpx 40rpx 60rpx 40rpx" class="flex">
						<u-tag class="m-r-20" text="日" mode="dark" @click="handleTime('日')"/>
						<u-tag class="m-r-20" text="本周" mode="light" @click="handleTime('周')"/>
						<u-tag class="m-r-20" text="月" mode="plain" @click="handleTime('月')"/>
						<u-tag text="年" mode="plain" @click="handleTime('年')"/>
				</view>
		</u-popup>

    <!-- 日 -->
		<u-calendar :show="isSelectTime" mode="single"
			:maxDate="calendar.maxDate"
			:minDate="calendar.minDate"
			:monthNum="calendar.monthNum"
			@close="isSelectTime=false"
			showLunar
			@confirm="confirmSelectTime"/>

   <!-- 年 -->
		<u-picker :show="isSelectTime3" :columns="yearDate" :defaultIndex="[3]" @confirm="confirmYear" />

    <!-- 月 -->
		<u-datetime-picker
				@confirm="datetimeConfirm"
				@cancel="isSelectTime2 = false"
				:show="isSelectTime2"
				v-model="currDate"
				:maxDate="new Date().getTime()"
				mode="year-month"
				ref="datetimePicker"
				:formatter="formatter"
		  />
	</view>
</template>

<script>
	import { teamRankingList, wallet, getTeamTotal, getTeamTable,getTeamLateralList,getTeamLateralTotal } from '@/common/api/customer.js'
	import { weekOrder } from '@/common/api/order.js'
	import activation from '@/pages/my/service/activation'
	import { mapState } from 'vuex'
	export default {
		components: {
			activation
		},
		data() {
			return {
				current: 0,
				list: [{
					name: '团队成员',
					type: ''
				}, {
					name: '周薪记录',
					type: 1
				}, {
					name: '业绩报表',
					type: 2
				}, {
					name: '团队/平级',
					type: 3
				}],
				// 团队奖平级奖
				teamList: [
					{ value: 2, name: '团队奖', isActive: true },
					{ value: 3, name: '平级奖', isActive: false }
				],
				listLevel: [
					{value: 2, name: '服务商'},
					{value: 3, name: '初级服务商'},
					{value: 4, name: '中级服务商'},
					{value: 5, name: '高级服务商'},
					{value: 6, name: '特级服务商'},
					{value: 7, name: '分红股东'}
				],
				status: 'loading',
				tabIndex: 0,
				pageNo: 0,
				rankList: [],
				extend: {},
				orderAwardList: [],
				sendFlag: 1,
				scrollTop: 0,
				walletInfo: {},
				billLevel: 2,
				currentIndex: 0,


				isShowTimeType: false,
				isSelectTime: false,
				isSelectTime2: false,
				isSelectTime3: false,
				calendar: {
					maxDate: '',
					minDate: '',
					monthNum: 13
				},
				yearDate:[['2021','2022','2023','2024','2025','2026']],
				currDate: null,
				startDateStr: new Date().getFullYear(),
				endDateStr: new Date().getFullYear(),
				queryTotal: {
					startDateStr:null,
					endDateStr:null
				},
				queryList: {
					pageNum:1,
					pageSize:1000,
					startDateStr:null,
					endDateStr:null,
				},
				tableList:[],
				reportTotal: {},
				month: null,
				year: new Date().getFullYear(),
				totalMoney: null,
				//查询团队平级奖
				teamLateralParmas : {
					pageNo:1,
					pageSize:10
				},
				teamLateralListData:[],
				teamLateralTotal:{},
			};
		},
		computed: {
			...mapState('user', ['userInfo'])
		},
		onShow() {
			this.rankList = [];
			this.tableList = [];
			this.orderAwardList = [];
			this.pageNo = 0;
			this.getWallet()
			if(this.current == 0) {
				this.getTeamRankingList()
			}
			if(this.current == 1) {
				this.getOrderAward()
			}
			if(this.current == 2) {
				this.getTotal()
				this.getTableDataList()
			}
			if(this.current == 3) {
				this.teamLateralListData = []
				this.teamLateralParmas.pageNo = 0
				this.getTeamLateralListFunc()
				this.getTeamLateralTotalFunc()
			}
		},
		onReachBottom() {
			if(this.current == 0) {
				this.getTeamRankingList()
			}
			if(this.current == 1) {
				this.getOrderAward()
			}
			if(this.current == 3 && this.status === 'loading') {
				this.getTeamLateralListFunc()
				this.getTeamLateralTotalFunc()
			}
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop
		},
		methods: {
			//切换tab
			tabChange(data){
				this.teamList.forEach(item => {
					if(item.value == data.value){
						item.isActive = true
						this.teamLateralParmas.type = item.value
					}else{
						item.isActive = false
					}
				})
				this.teamLateralListData = []
				this.teamLateralParmas.pageNo = 0
				this.getTeamLateralListFunc()
				this.getTeamLateralTotalFunc()
			},
			levelClick(e){
				this.billLevel = e.value;
				this.pageNo = 0;
				this.rankList = []
				this.getTeamRankingList()
			},
			toWeeklyRecords(item) {
				uni.navigateTo({
					url: '/pages/my/service/weeklyRecords?orderId=' + item.orderId
				})
			},
			toBuy() {
				uni.navigateTo({
					url: '/pages/product/panicBuying?areaId=3'
				})
			},
			toActivation() {
				this.$refs.activation.show = true
			},
			// 获取用户钱包
			getWallet() {
				wallet().then(res => {
					this.walletInfo = res.data || {}
				})
			},
			resetData() {
				this.pageNo = 0
				this.rankList = []
				this.extend = {}
				this.orderAwardList = []
				this.tabIndex = 0
				this.sendFlag = 1
			},
			getOrderAward(walletType) {
				this.pageNo++
				this.status = 'loading'
				weekOrder({pageNo: this.pageNo, pageSize: 10, rewardType: 1, sendFlag: this.sendFlag}).then(res => {
					this.orderAwardList = this.orderAwardList.concat(res.data)
					if (res.data.length < 10) {
						this.status = 'nomore'
					}
				})
			},
			getTeamRankingList() {
				this.status = 'loading'
				this.pageNo++
				teamRankingList({ pageNo: this.pageNo, pageSize: 10, productArea: 3, isFacilitator: true, billLevel:this.billLevel }).then(res=>{
					uni.hideLoading()
					if(res.code == 200) {
						this.rankList = this.rankList.concat(res.data)
						this.extend = res.extend || {}
						this.totalMoney = res.extend.taxationMonetary
						if (res.data.length < 10) {
							this.status = 'nomore'
						}
					}
				}).catch(err=>{
					uni.hideLoading()
				})
			},
			selectTab(index) {
				this.resetData()
				this.tabIndex = index
				if(this.tabIndex == 0) {
					this.sendFlag = 1
				}
				if(this.tabIndex == 1) {
					this.sendFlag = 0
				}
				this.getOrderAward()
			},
			handelTab(e) {
				this.current = e.index
				this.resetData()
				if(this.current == 0) {
					this.getTeamRankingList()
				}
				if(this.current == 1) {
					this.getOrderAward()
				}
				if(this.current == 2) {
					this.getTotal()
					this.getTableDataList()
				}
				if(this.current == 3) {
					this.teamLateralParmas.pageNo = 0
					this.getTeamLateralListFunc()
					this.getTeamLateralTotalFunc()
				}
			},
			// 查询团队平级奖
			getTeamLateralListFunc(){
				this.teamLateralParmas.pageNo++
				this.status = 'loading'
				getTeamLateralList(this.teamLateralParmas).then(res => {
					this.teamLateralListData = this.teamLateralListData.concat(res.data)
					if (res.data.length < 10) {
						this.status = 'nomore'
					}
				})
			},
			// 查询团队平级奖 汇总
			getTeamLateralTotalFunc(){
				getTeamLateralTotal(this.teamLateralParmas).then(res => {
					this.teamLateralTotal = res.data
				})
			},
			copyCode(code) {
				let that = this
				uni.setClipboardData({
					data: code,
					success: function() {
						that.$msg('复制成功')
					}
				})
			},

			handleTime(type){
				this.selectTimeType = type
				switch (type) {
					case '日':
							this.isSelectTime = true
							break;
					case '周':
							const { startDate, endDate } = this.getThisWeekDates();
							this.startDateStr = startDate
							this.endDateStr = endDate
							this.year = null
							this.month = null
							this.getTotal()
							this.getTableDataList()
							break;
					case '月':
							this.isSelectTime2 = true
							break;
					case '年':
							this.isSelectTime3 = true
							break;
				}
				this.isShowTimeType=false
			},

			confirmSelectTime(val){
				this.startDateStr = val[0]
				this.endDateStr = val[0]
				this.year = null
				this.month = null
				this.isSelectTime = false
				this.getTotal()
				this.getTableDataList()
			},

			confirmYear(e){
				this.year = e.value[0]
				this.month = null
				this.isSelectTime3 = false
				this.startDateStr = e.value[0]
				this.endDateStr = e.value[0]
				this.getTotal()
				this.getTableDataList()
			},

			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				return value
			},

			//
			datetimeConfirm(e){
				this.isSelectTime2 = false
				this.year = null
				this.month = uni.$u.timeFormat(e.value, 'yyyy-mm')
				this.startDateStr = uni.$u.timeFormat(e.value, 'yyyy-mm')
				this.endDateStr = uni.$u.timeFormat(e.value, 'yyyy-mm')
				this.getTotal()
				this.getTableDataList()
			},

			//获取本周
			getThisWeekDates() {
				const today = new Date();
				const dayOfWeek = today.getDay();
				const startDate = new Date(today);
				startDate.setDate(today.getDate() - dayOfWeek + 1); // 设置为本周的第一天（星期一）

				const endDate = new Date(today);
				endDate.setDate(today.getDate() + (7 - dayOfWeek)); // 设置为本周的最后一天（星期日）

				const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
				const startDateFormatted = startDate.toLocaleDateString('zh-CN', options);
				const endDateFormatted = endDate.toLocaleDateString('zh-CN', options);

				return { startDate: startDateFormatted.replace(/\//g, '-'), endDate: endDateFormatted.replace(/\//g, '-') };
			},

			// 统计
			getTotal(){
				this.queryTotal.startDateStr = this.startDateStr
				this.queryTotal.endDateStr = this.endDateStr
				this.queryTotal.year = this.year
				this.queryTotal.month = this.month
				if(this.year){
					this.queryTotal.startDateStr = null
					this.queryTotal.endDateStr = null
					this.queryTotal.month = null
				}
				if(this.month){
					this.queryTotal.startDateStr = null
					this.queryTotal.endDateStr = null
					this.queryTotal.year = null
				}
				getTeamTotal(this.queryTotal).then(res=>{
					if(res.code == 200){
						this.reportTotal = res.data
					}
				})
			},
			// table列表
			getTableDataList(){
				this.queryList.startDateStr = this.startDateStr
				this.queryList.endDateStr = this.endDateStr
				this.queryList.year = this.year
				this.queryList.month = this.month
				if(this.year){
					this.queryList.startDateStr = null
					this.queryList.endDateStr = null
					this.queryList.month = null
				}
				if(this.month){
					this.queryList.startDateStr = null
					this.queryList.endDateStr = null
					this.queryList.year = null
				}
				getTeamTable(this.queryList).then(res=>{
					if(res.code == 200){
						this.tableList = res.data
					}
				})
			}
		}
	}
</script>

<style lang="scss">
page {
	background: #f2f2f2;
}
</style>
<style lang="scss" scoped>
.btnBox{
	width: auto !important;
	overflow-x: scroll;
	.btnItem{
		line-height: 80rpx;
		background: #f3f3f3;
	}
}
.boxContent{
	background: linear-gradient( 42deg, #FF0804 0%, #FC7844 100%);
	box-shadow: 0px 2px 10px 1px rgba(250,49,33,0.24);
}
.borderWidth{
	width: 2rpx;
	height: 120rpx;
	background: #ffffff;
}
.tableHeader, .tableContent{
	text-align: center;
	view:nth-child(1){
		width: 30%;
	}
	view:nth-child(2){
		width: 35%;
		line-height: 40rpx;
		view{
			width: 100%;
			line-height: 40rpx;
		}
	}
	view:nth-child(3){
		width: 15%;
	}
	view:nth-child(4){
		width: 20%;
	}
}
.tableContent{
	view{
		line-height: 70rpx;
	}
}
.head {
	background-image: url('/static/my/service-bg.png');
	background-size: 100% 100%;
}
.copy-btn {
	border: 2rpx solid #808080;
	color: #808080;
	font-size: 20rpx;
	padding: 2rpx 10rpx;
	margin-left: 20rpx;
	border-radius: 6rpx;
}
.level {
	background: linear-gradient(42deg, #FF0804 0%, #FC7844 100%);
	box-shadow: 0 2rpx 10rpx 1rpx rgba(250,49,33,0.24);
	color: #ffffff;
	font-size: 24rpx;
	padding: 4rpx 10rpx;
	border-radius: 8rpx;
	margin-left: 20rpx;
	min-width: 96rpx;
	text-align: center;
}
.tab-item {
	width: 240rpx;
	height: 64rpx;
	box-shadow: 0rpx 2rpx 10rpx 1rpx rgba(250,49,33,0.24);
	color: #FA3121;
	font-size: 30rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	border: 1px solid #FA3121;
	border-radius: 16rpx;
}
.tab-item-active {
	background: linear-gradient(42deg, #FF0804 0%, #FC7844 100%);
	color: #ffffff;
	border: none !important;
}
.buy-btn {
	width: 110rpx;
	height: 50rpx;
	border-radius: 8rpx;
	border: 1rpx solid #FA3121;
	font-size: 28rpx;
	color: #FE1A13;
	display: flex;
	justify-content: center;
	align-items: center;
}
.fg-btn {
	background-color: #FA3121;
	color: #ffffff !important;
}
.find-btn {
	background: linear-gradient(42deg, #FF0804 0%, #FC7844 100%);
	color: #ffffff !important;
	border-radius: 50rpx !important;
}
::v-deep .btnBox .u-tabs__wrapper__nav__line{
	display: none !important;
}
::v-deep .btnBox .u-tabs__wrapper__nav__item__text{
	font-size: 24rpx !important;
	border-radius: 8rpx !important;
	padding: 0 10rpx !important;
}
.widthName{
	width: 200rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}
.boxss{
	align-items: center;
	font-size: 26rpx;
	border: 2rpx solid #CCCCCC;
	min-width: 200rpx;
	height: 60rpx;
}
.activeStyle{
	border: 2rpx solid #E60000 !important;
	color: red !important;
}
.styleBtn{
	border-radius: 10rpx;
	text-align: center;
	line-height: 70rpx;
	flex:1;
	color: #000000;
	border: 2rpx solid gray;
	margin-right: 20rpx;
	font-size: 15px;
	font-weight: bold;
}
.styleBtn:last-child{
	margin-right: 0rpx;
}
</style>
